<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="never">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="申请时间" prop="createTime">
              <el-date-picker
                v-model="queryParams.createTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                clearable
                style="width: 280px"
              />
            </el-form-item>

            <el-form-item label="预算部门" prop="deptCode">
              <el-select
                v-model="queryParams.deptCode"
                placeholder="全部"
                clearable
                filterable
                collapse-tags
                @keyup.enter="handleQuery"
                collapse-tags-tooltip
              >
                <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptCode" />
              </el-select>
            </el-form-item>

            <el-form-item label="申请主题" prop="topic">
              <el-input v-model="queryParams.topic" placeholder="请输入申请主题" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <!--            <el-form-item label="状态" prop="status">-->
            <!--              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>-->
            <!--                <el-option v-for="dict in comp_status" :key="dict.value" :label="dict.label" :value="dict.value" />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['execute:complaint:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" icon="Download" @click="handleExport" v-hasPermi="['execute:complaint:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['execute:complaint:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['execute:complaint:remove']"
              >删除
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table border v-loading="loading" :data="complaintList" :style="tableStyle" @selection-change="handleSelectionChange" class="enhanced-table">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键id" align="center" prop="id" v-if="false" show-overflow-tooltip />
        <el-table-column label="申诉编码" align="center" prop="code" />
        <el-table-column label="申请主题" align="center" prop="topic" show-overflow-tooltip>
          <template #default="scope">
            <el-link :underline="true" type="primary" @click="handleOpen(scope.row)">
              {{ scope.row.topic }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="预算部门编码" align="center" prop="deptCode" />
        <el-table-column label="预算部门" align="center" prop="deptName" />
        <el-table-column label="状态" align="center" prop="status" width="140">
          <template #default="scope">
            <dict-tag :options="comp_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="申请时间" align="center" prop="createTime" width="200"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看" placement="top" >
              <el-button link type="primary" icon="View" @click="handleOpen(scope.row)" v-hasPermi="['execute:complaint:get']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top" v-if="scope.row.status === '0'">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['execute:complaint:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-if="scope.row.status === '0' || scope.row.status === '1'">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['execute:complaint:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="提交" placement="top" v-if="scope.row.status === '0'">
              <el-button link type="primary" icon="Position" @click="handleSubmit(scope.row)" v-hasPermi="['execute:complaint:submit']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改申诉对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" style="width: 500px" append-to-body>
      <el-form ref="complaintFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="申请主题" prop="topic">
          <el-input v-model="form.topic" placeholder="请输入申请主题" maxlength="50" show-word-limit :disabled="disabled" />
        </el-form-item>

        <el-form-item label="申诉内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入申诉内容" maxlength="500" show-word-limit :disabled="disabled" />
        </el-form-item>

        <el-form-item label="处理结果" prop="result" v-if="disabled">
          <el-input v-model="form.result" type="textarea" placeholder="请输入处理结果" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Complaint" lang="ts">
import { addComplaint, delComplaint, getComplaint, listComplaint, submitComplaint, updateComplaint } from '@/api/fill/execute/complaint';
import { ComplaintForm, ComplaintQuery, ComplaintVO } from '@/api/fill/execute/complaint/types';
import { ref } from 'vue';
import { DeptVO } from '@/api/budget/budgetDept/types';
import { getDeptList } from '@/api/budget/budgetDept';

import { formatDateTime } from '@/hooks/useDate';
import { useTableHeight } from "@/hooks/useMethod";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { comp_status } = toRefs<any>(proxy?.useDict('comp_status'));

const deptList = ref<DeptVO[]>([]);
/*预算部门列表*/
const getBudgetDeptList = () => {
  getDeptList(1).then((res) => {
    deptList.value = res.data;
  });
};
const complaintList = ref<ComplaintVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const complaintFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ComplaintForm = {
  id: undefined,
  code: undefined,
  topic: undefined,
  status: undefined,
  content: undefined,
  result: undefined
};
const data = reactive<PageData<ComplaintForm, ComplaintQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    topic: undefined,
    deptCode: undefined,
    createTime: undefined,
    startTime: undefined,
    endTime: undefined,
    type: 'my'
  },
  rules: {
    topic: [{ required: true, message: '申请主题不能为空', trigger: 'blur' }],

    content: [{ required: true, message: '申诉内容不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/*开单日期计算属性*/
watch(
  () => queryParams.value.createTime,
  (newDates) => {
    if (newDates && newDates.length === 2) {
      const startDate = new Date(newDates[0]);
      startDate.setHours(0, 0, 0, 0);
      queryParams.value.startTime = formatDateTime(startDate);

      const endDate = new Date(newDates[1]);
      endDate.setHours(23, 59, 59, 999);
      queryParams.value.endTime = formatDateTime(endDate);
    } else {
      queryParams.value.startTime = undefined;
      queryParams.value.endTime = undefined;
    }
  },
  { deep: true }
);
/** 查询申诉列表 */
const getList = async () => {
  loading.value = true;
  const res = await listComplaint(queryParams.value);
  complaintList.value = res.data.records;
  total.value = res.data.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  complaintFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ComplaintVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  disabled.value = false;
  reset();
  dialog.visible = true;
  dialog.title = '添加申诉';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ComplaintVO) => {
  disabled.value = false;
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getComplaint(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改申诉';
};
//框是否显示
const disabled = ref(false);

const handleOpen = async (row?: ComplaintVO) => {
  disabled.value = true;
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getComplaint(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '申诉详情';
};

/** 提交按钮 */
const submitForm = () => {
  complaintFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateComplaint(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addComplaint(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ComplaintVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除选中的数据项？').finally(() => (loading.value = false));
  await delComplaint(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/*提交*/
const handleSubmit = async (row?: ComplaintVO) => {
  await proxy?.$modal.confirm('是否确认提交该申诉？').finally(() => (loading.value = false));
  submitComplaint(row.id).then((res) => {
    proxy?.$modal.msgSuccess('提交成功');
    getList();
  });
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'execute/complaint/export',
    {
      ...queryParams.value
    },
    `我的申诉.xlsx`
  );
};

const tableStyle = useTableHeight(showSearch, {
  withSearch: '61vh',
  withoutSearch: '71vh'
});

onMounted(() => {
  getBudgetDeptList();
  getList();
});
</script>
